# -*- coding: utf-8 -*-
from odoo import models, fields, api, _
from odoo.exceptions import UserError, ValidationError
from odoo.tools import float_is_zero, float_compare
import odoo.addons.decimal_precision as dp


class DepartmentApproveModelInfo(models.Model):
    _inherit = 'department.approve.model.info'

    model = fields.Selection(selection_add=[('hr.payment.request', '付款单')])


class ResPartnerBank(models.Model):
    _inherit = 'res.partner.bank'

    def name_get(self):
        result = []
        for record in self:
            name = record.acc_number
            if record.bank_id:
                name = "%s:%s" % (record.bank_id.name_get()[0][1], name)
            result.append((record.id, name))
        return result

    # @api.depends('bank_id','acc_number')
    # def name_get(self):
    #     res = []
    #     for record in self:
    #         name = record.name
    #         if record.bank_id.name:
    #             name = record.bank_id.name + '-' + record.acc_number
    #         res.append((record.id, name))
    #     return res


class HrPaymentRequest(models.Model):
    """
    付款申请
    """

    _name = 'hr.payment.request'
    _inherit = ['mail.thread', 'mail.activity.mixin', 'base.approve']
    _order = 'id desc'
    _description = u'付款申请'
    approval_record_ids = fields.One2many('approval.records', 'res_id',
                                          domain=[('res_model', '=', 'hr.payment.request')])
    approve_flow_ids = fields.One2many('approve.flow', 'res_id', domain=[('res_model', '=', 'hr.payment.request')])

    partner_id = fields.Many2one('res.partner', domain=['|', ('supplier_rank', '>', 0), ('customer_rank', '>', 0)],
                                 string=u'收款单位')

    name = fields.Char(copy=False, string=u'单号')
    line_ids = fields.One2many('hr.payment.request.line', 'request_id')
    approved_id = fields.Many2one('res.users', help=u'记录一下谁审核通过了这张单据')

    partner_name = fields.Char(string=u'收款人')
    bank_id = fields.Many2one('res.partner.bank', string=u'银行账户', domain="[('partner_id', '=', partner_id)]")
    bank_number = fields.Char(string=u'账号号码')
    bank_name = fields.Char(string=u'开户银行')
    attachment_number = fields.Integer('附件数量', compute='_compute_attachment_number')

    def action_get_attachment_view(self):
        res = self.env['ir.actions.act_window'].for_xml_id('base', 'action_attachment')
        res['domain'] = [('res_model', '=', 'hr.payment.request.line'), ('res_id', 'in', self.line_ids.ids)]
        res['context'] = {
            'default_res_model': 'hr.payment.request',
            'default_res_id': self.id,
            'create': False,
            'edit': False,
        }
        return res

    def _compute_attachment_number(self):
        for sheet in self:
            sheet.attachment_number = sum(sheet.line_ids.mapped('attachment_number'))

    def _track_subtype(self, init_values):
        self.ensure_one()
        if 'state' in init_values and self.state == 'approve':
            return self.env.ref('hr_payment_request.mt_expense_approved')
        elif 'state' in init_values and self.state == 'rejected':
            return self.env.ref('hr_payment_request.mt_expense_refused')
        elif 'state' in init_values and self.state == 'done':
            return self.env.ref('hr_payment_request.mt_expense_paid')
        return super(HrPaymentRequest, self)._track_subtype(init_values)

    user_id = fields.Many2one('res.users', 'Manager', readonly=False, copy=False,
                              states={'draft': [('readonly', False)]}, tracking=True)

    def _message_auto_subscribe_followers(self, updated_values, subtype_ids):
        res = super(HrPaymentRequest, self)._message_auto_subscribe_followers(updated_values, subtype_ids)
        if updated_values.get('employee_id'):
            employee = self.env['hr.employee'].browse(updated_values['employee_id'])
            if employee.user_id:
                res.append((employee.user_id.partner_id.id, subtype_ids, False))
        return res

    def mail_get_link(self):
        """ 获取报价单form视图的url """
        base_url = self.env["ir.config_parameter"].sudo().get_param("web.base.url")
        action = self.env.ref("hr_payment_request.action_my_hr_payment_request_to_approve").id
        web_url = "/web?#id=%d&action=%d&view_type=form" % (self.id, action)
        return base_url + web_url

    def send_to_approve_email(self, user_id):

        mail_template = self.env.ref('hr_payment_request.template_hr_payment_request')
        mail_template.send_mail(self.id, force_send=True,
                                email_values={'email_to': user_id.partner_id.email})

    @api.onchange('partner_id')
    def onchange_partner_id_for_bank_info(self):
        # self.rt_company_id = self.employee_id.rt_company_id
        # self.bank_partner = self.partner_id.name
        if self.partner_id and self.partner_id.bank_ids:
            self.bank_id = self.partner_id.bank_ids[0]

            self.partner_name = self.partner_id.name

    @api.onchange('bank_id')
    def onchange_bank_id(self):
        if self.bank_id:
            self.bank_number = self.bank_id.acc_number
            self.bank_name = self.bank_id.bank_name

    def set_to_done(self):
        self.state = 'approve'

    _sql_constraints = {
        ('name_uniq', 'unique(name)',
         '单号必须唯一!')
    }
    description = fields.Char(string=u'借付款事由')
    employee_id = fields.Many2one('hr.employee',
                                  copy=False,
                                  string=u'员工',
                                  default=lambda self: self.env['hr.employee'].search([('user_id', '=', self.env.uid)],
                                                                                      limit=1))
    barcode = fields.Char(related='employee_id.barcode', string=u'工号')
    department_id = fields.Many2one('hr.department', string=u'部门')
    # 付款记录
    payment_ids = fields.One2many('account.payment', 'res_id', domain=[('res_model', '=', 'hr.payment.request'),
                                                                       ('payment_type', '=', 'outbound')])

    @api.onchange('employee_id')
    def _onchange_employee_id(self):
        self.department_id = self.employee_id.department_id
        self.user_id = self.employee_id.sudo().user_id.id

    @api.depends('payment_ids')
    def _get_paid_amount(self):
        for record in self:
            record.paid_amount = sum(payment.amount for payment in record.payment_ids)

    # 已支付金额
    paid_amount = fields.Float(compute=_get_paid_amount)

    def _compute_has_payment_ids(self):
        for sheet in self:

            if sheet.payment_ids:
                sheet.has_payment_ids = True
            else:
                sheet.has_payment_ids = False

    def set_to_done(self):
        self.state = 'approve'

    has_payment_ids = fields.Boolean(compute=_compute_has_payment_ids)

    company_id = fields.Many2one('res.company', default=lambda self: self.env.user.company_id)

    apply_date = fields.Date(default=fields.Date.context_today)
    amount = fields.Float(string='金额', readonly=True,
                          states={'draft': [('readonly', False)], 'reported': [('readonly', False)],
                                  'refused': [('readonly', False)]})

    remark = fields.Text(string='备注')

    def get_total_amount(self):
        return self.amount

    @api.constrains('amount')
    def _check_amount(self):
        for wizard in self:
            if not wizard.amount > 0.0:
                raise ValidationError('申请金额必须大于0')

    state = fields.Selection([
        ('draft', u'草稿'),
        ('cancel', u'被拒'),
        ('to approve', u'审核中'),
        ('rejected', u'被拒'),
        ('approve', u'待付款'),
        ('done', u'已支付'),
    ], string=u"状态", default='draft', track_visibility='onchange')

    def post(self):

        context = {'default_payment_type': 'outbound', 'default_amount': self.amount - self.paid_amount,

                   }

        return {
            'name': _('payment'),
            'view_type': 'form',
            'view_mode': 'form',
            # 'view_id': False,
            'res_model': 'hr.payment.request.wizard',
            'domain': [],
            'context': dict(context, active_ids=self.ids),
            'type': 'ir.actions.act_window',
            'target': 'new',
        }

    @api.model
    def create(self, vals):
        vals['name'] = self.env['ir.sequence'].next_by_code('hr.payment.request') or '/'
        return super(HrPaymentRequest, self).create(vals)


class HrPaymentRequestLine(models.Model):
    _name = 'hr.payment.request.line'
    _description = '付款明细'
    request_id = fields.Many2one('hr.payment.request',ondelete='cascade')
    name = fields.Char(string=u'文件名称')
    attachment_number = fields.Integer('Number of Attachments', compute='_compute_attachment_number')
    def _compute_attachment_number(self):
        attachment_data = self.env['ir.attachment'].read_group([('res_model', '=', 'hr.payment.request.line'), ('res_id', 'in', self.ids)], ['res_id'], ['res_id'])
        attachment = dict((data['res_id'], data['res_id_count']) for data in attachment_data)
        for expense in self:
            expense.attachment_number = attachment.get(expense.id, 0)

    def action_get_attachment_view(self):
        self.ensure_one()
        res = self.env['ir.actions.act_window'].for_xml_id('base', 'action_attachment')
        res['domain'] = [('res_model', '=', 'hr.payment.request.line'), ('res_id', 'in', self.ids)]
        res['context'] = {'default_res_model': 'hr.payment.request.line', 'default_res_id': self.id}
        return res
